
import Component from 'vue-class-component';
import Vue from 'vue';
import DateUtils from '@/utils/DateUtils';
import Header from '@/utils/Header';
import help from './help.md';
const regexData1 = [
    {
        name: 'js 转 ts',
        id: 1,
        isGlobal: true,
        isMultiLine: true,
        items: [
            { id: '1', regex: '^    (\\\w*): function', replace: '$1' },
            { id: '2', regex: '^    },', replace: '}' },
        ],
    },
];

@Component({

})
export default class MultiRegex extends Vue {
    public input = '';
    public output = '';
    public selected = regexData1[0];
    public regexData = regexData1;

    public created() {
        this.getLocal();
        Header.setHeader({
            title: '正则多步替换',
            desp: '',
            help,
        });
    }

    public getLocal() {
        const s = localStorage.getItem('multi-regex');
        if (s) {
            const o = JSON.parse(s);
            console.log(o);
            this.regexData = o;
            this.selected = this.regexData[0];
        }
    }

    public setLocal() {
        localStorage.setItem('multi-regex', JSON.stringify(this.regexData));
    }

    public onTransfer() {

        let s = this.input;
        let attr = '';
        if (this.selected.isGlobal) {
            attr += 'g';
        }
        if (this.selected.isMultiLine) {
            attr += 'm';
        }

        for (const item of this.selected.items) {
            if (item.regex) {
                const r = new RegExp(item.regex, attr);
                s = s.replace(r, item.replace);

            }
        }
        this.output = s;
        this.setLocal();
    }
    public onClearCache() {
        localStorage.removeItem('multi-regex');
    }

    public onAddItem(index) {
        this.selected.items.splice(index + 1, 0, {
            regex: '',
            replace: '',
            id: DateUtils.formatDay(new Date()),
        });
    }

    public onDelItem(index) {
        if (this.selected.items.length === 1) {
            const first = this.selected.items[0];
            first.regex = '';
            first.replace = '';
        } else {
            this.selected.items.splice(index, 1);
        }
    }
}
